{% extends "base.html" %}

{% block content %}
<div class="card">
    <h2><i class="fas fa-puzzle-piece"></i> 插件管理</h2>
    
    <!-- 响应式文件浏览器 -->
    <div class="file-browser">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
            <span class="breadcrumb-item" data-path="">根目录</span>
            {% for part in current_path.split('/') if part %}
            <span class="breadcrumb-separator">/</span>
            <span class="breadcrumb-item" data-path="{{ '/'.join(current_path.split('/')[:loop.index]) }}">{{ part }}</span>
            {% endfor %}
        </div>
        
        <!-- 操作按钮组 -->
        <div class="file-actions">
            <div class="btn-group">
                <button onclick="createNewFile()" class="btn btn-primary">
                    <i class="fas fa-file"></i> 新建文件
                </button>
                <button onclick="createNewFolder()" class="btn btn-primary">
                    <i class="fas fa-folder"></i> 新建文件夹
                </button>
                <button onclick="uploadFile()" class="btn btn-info">
                    <i class="fas fa-upload"></i> 上传
                </button>
                <button onclick="refreshFileList()" class="btn btn-secondary">
                    <i class="fas fa-sync"></i> 刷新
                </button>
            </div>
        </div>
        
        <!-- 响应式文件列表 -->
        <div class="file-list">
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>名称</th>
                            <th class="hide-mobile">类型</th>
                            <th class="hide-mobile">时间</th>
                            <th class="hide-tablet">修改时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="fileListBody">
                        <tr>
                            <td colspan="5" class="loading">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 响应式编辑器模态框 -->
<div id="editorModal" class="modal">
    <div class="modal-content responsive-modal" style="z-index: 1001; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);">
        <div class="modal-header">
            <h3 id="editorTitle">文件编辑器</h3>
            <span class="close" onclick="closeEditor()">×</span>
        </div>
        <div class="modal-body">
            <!-- 编辑器工具栏 -->
            <div class="editor-toolbar">
                <div class="toolbar-group">
                    <button onclick="editorUndo()" class="btn btn-sm">
                        <i class="fas fa-undo"></i> 撤销
                    </button>
                    <button onclick="editorRedo()" class="btn btn-sm">
                        <i class="fas fa-redo"></i> 重做
                    </button>
                </div>
                <div class="toolbar-group">
                    <button onclick="editorFind()" class="btn btn-sm">
                        <i class="fas fa-search"></i> 查找
                    </button>
                    <button onclick="editorReplace()" class="btn btn-sm">
                        <i class="fas fa-exchange-alt"></i> 替换
                    </button>
                </div>
                <div class="toolbar-group">
                    <button onclick="reloadFile()" class="btn btn-sm">
                        <i class="fas fa-sync"></i> 重载
                    </button>
                </div>
                <div class="editor-status">
                    <span id="editorStatus">就绪</span>
                </div>
            </div>
            
            <!-- 编辑器容器 -->
            <div id="editorContainer" class="editor-container">
                <div id="editor"></div>
            </div>
        </div>
        <div class="modal-footer">
            <button onclick="saveFile()" class="btn btn-success">
                <i class="fas fa-save"></i> 保存
            </button>
            <button onclick="closeEditor()" class="btn btn-secondary">
                取消
            </button>
        </div>
    </div>
</div>

<!-- 操作确认模态框 -->
<div id="actionModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="actionModalTitle">操作确认</h3>
            <span class="close" onclick="closeActionModal()">×</span>
        </div>
        <div class="modal-body">
            <p id="actionModalMessage"></p>
        </div>
        <div class="modal-footer">
            <button id="actionConfirmBtn" class="btn btn-danger">确认</button>
            <button onclick="closeActionModal()" class="btn btn-secondary">取消</button>
        </div>
    </div>
</div>

<style>
/* 插件管理页面特定样式 */
.file-browser {
    background: var(--card-bg);
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(179, 224, 255, 0.4);
}

/* 面包屑导航 */
.breadcrumb {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 0.5rem;
    padding: 1rem;
    background: rgba(230, 247, 255, 0.5);
    border-radius: 8px;
    margin-bottom: 1.5rem;
    border: 1px solid var(--secondary-color);
}

.breadcrumb-item {
    cursor: pointer;
    padding: 0.5rem 0.8rem;
    border-radius: 4px;
    transition: all 0.3s ease;
    color: var(--text-color);
    font-weight: 500;
}

.breadcrumb-item:hover {
    background: var(--secondary-color);
    color: var(--accent-color);
}

.breadcrumb-separator {
    color: var(--light-text);
    font-weight: bold;
}

/* 文件操作按钮组 */
.file-actions {
    margin-bottom: 1.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--secondary-color);
}

.btn-group {
    display: flex;
    flex-wrap: wrap;
    gap: 0.8rem;
}

/* 响应式文件列表 */
.file-list {
    width: 100%;
    overflow: hidden;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
    border-radius: 8px;
    border: 1px solid var(--secondary-color);
}

.file-list table {
    width: 100%;
    border-collapse: collapse;
    min-width: 600px;
    background: white;
}

.file-list th,
.file-list td {
    padding: 1rem;
    text-align: left;
    border-bottom: 1px solid var(--secondary-color);
}

.file-list th {
    background: rgba(179, 224, 255, 0.3);
    font-weight: 600;
    color: var(--text-color);
    white-space: nowrap;
}

.file-list tr:hover {
    background: rgba(179, 224, 255, 0.1);
}

/* 文件图标和名称 */
.file-icon {
    margin-right: 0.5rem;
    width: 20px;
    text-align: center;
}

/* 操作按钮单元格 - 修改为文字按钮 */
.file-actions-cell {
    white-space: nowrap;
}

/* 在文件浏览器样式中添加 */
@media (min-width: 769px) {
    .mobile-actions {
        display: none !important;
    }
}

@media (max-width: 768px) {
    .desktop-actions {
        display: none !important;
    }
    
    .mobile-actions {
        display: block;
    }
}

/* 桌面端操作按钮 - 修改为文字按钮 */
.desktop-actions {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.action-btn {
    padding: 0.4rem 0.8rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.85rem;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
    min-width: auto;
    white-space: nowrap;
}

.btn-edit {
    background: var(--info-color);
    color: white;
}

.btn-download {
    background: var(--success-color);
    color: white;
}

.btn-rename {
    background: var(--warning-color);
    color: white;
}

.btn-delete {
    background: var(--error-color);
    color: white;
}

.action-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

/* 移动端文件信息 */
.mobile-only {
    display: none;
}

@media (max-width: 768px) {
    .mobile-only {
        display: block;
        font-size: 0.8em;
        color: #666;
        margin-top: 5px;
    }
    
    .file-info-cell {
        padding: 12px 8px !important;
    }
    
    .file-info-content {
        display: flex;
        align-items: flex-start;
        gap: 10px;
    }
    
    .file-details {
        flex: 1;
        min-width: 0;
    }
    
    .file-name {
        font-weight: 500;
        color: #333;
        margin-bottom: 4px;
        word-break: break-word;
    }
    
    .file-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        font-size: 0.75em;
    }
    
    .file-meta span {
        background: #f0f0f0;
        padding: 2px 6px;
        border-radius: 4px;
        white-space: nowrap;
    }
    
    /* 移动端操作按钮组 - 修改为文字按钮 */
    .mobile-actions {
        display: flex;
    }
    
    .mobile-action-buttons {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
    }
    
    .mobile-action-btn {
        padding: 6px 10px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        gap: 4px;
        border: none;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s ease;
        min-width: auto;
        white-space: nowrap;
    }
    
    .mobile-action-btn:hover {
        transform: scale(1.05);
    }
    
    /* 隐藏桌面端操作 */
    .desktop-actions {
        display: none;
    }
    
    /* 调整表格布局 */
    .file-list table {
        min-width: auto;
    }
    
    .file-list th.hide-mobile,
    .file-list td.hide-mobile,
    .file-list th.hide-tablet,
    .file-list td.hide-tablet {
        display: none;
    }
    
    .file-actions-cell {
        padding: 8px !important;
    }
}

/* 触摸反馈 */
.mobile-action-btn:active {
    transform: scale(0.95);
}

/* 文件图标大小 */
.file-icon {
    font-size: 1.2em;
    margin-top: 2px;
    flex-shrink: 0;
}

/* 响应式面包屑 */
@media (max-width: 768px) {
    .breadcrumb {
        font-size: 0.8em;
        padding: 8px;
        overflow-x: auto;
        white-space: nowrap;
    }
    
    .breadcrumb-item {
        padding: 4px 6px;
        font-size: 0.9em;
    }
}

/* 确保按钮组不超出范围 */
.form-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    margin-top: 30px;
    border-top: 1px solid #eee;
    padding-top: 20px;
    max-width: 100%;
    overflow: hidden;
}

.form-actions .btn {
    flex: 1;
    min-width: 120px;
    max-width: 200px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.form-select {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid var(--secondary-color);
    border-radius: 4px;
    background: white;
    font-size: 0.9rem;
}

/* 编辑器模态框 */
.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
    align-items: center;
    justify-content: center;
}

.responsive-modal {
    background-color: white;
    border-radius: 12px;
    width: 90%;
    max-width: 1000px;
    max-height: 90vh;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: column;
}

.modal-header {
    padding: 1.5rem;
    border-bottom: 1px solid var(--secondary-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: var(--header-bg);
}

.modal-header h3 {
    margin: 0;
    color: var(--text-color);
    font-size: 1.4rem;
}

.close {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    transition: color 0.3s ease;
}

.close:hover {
    color: #333;
}

.modal-body {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* 编辑器工具栏 */
.editor-toolbar {
    padding: 1rem;
    background: #f8f9fa;
    border-bottom: 1px solid var(--secondary-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.toolbar-group {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.editor-status {
    color: var(--light-text);
    font-size: 0.9rem;
}

/* 编辑器容器 */
.editor-container {
    flex: 1;
    min-height: 400px;
    overflow: hidden;
}

#editor {
    width: 100%;
    height: 100%;
    min-height: 400px;
}

.modal-footer {
    padding: 1.5rem;
    border-top: 1px solid var(--secondary-color);
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
    background: #f8f9fa;
}

/* 操作确认模态框 */
#actionModal .modal-content {
    background-color: white;
    border-radius: 12px;
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

/* 加载和空状态 */
.loading, .empty, .error {
    text-align: center;
    padding: 2rem;
    color: var(--light-text);
}

.error {
    color: var(--error-color);
}

/* 隐藏类用于响应式设计 */
.hide-mobile {
    display: table-cell;
}

.hide-tablet {
    display: table-cell;
}

/* 响应式设计 - 平板 */
@media (max-width: 1024px) {
    .file-actions {
        flex-direction: column;
        align-items: stretch;
    }
    
    .btn-group {
        justify-content: center;
    }
    
    .hide-tablet {
        display: none;
    }
    
    .responsive-modal {
        width: 95%;
        margin: 1rem;
    }
    
    .editor-toolbar {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.8rem;
    }
}

/* 响应式设计 - 手机 */
@media (max-width: 768px) {
    .breadcrumb {
        padding: 0.8rem;
        font-size: 0.9rem;
    }
    
    .breadcrumb-item {
        padding: 0.4rem 0.6rem;
    }
    
    .file-actions {
        padding: 0.8rem;
    }
    
    .btn-group {
        width: 100%;
        justify-content: space-around;
    }
    
    .btn {
        flex: 1;
        min-width: auto;
        padding: 0.8rem 0.5rem;
        font-size: 0.9rem;
    }
    
    .file-list th,
    .file-list td {
        padding: 0.8rem;
        font-size: 0.9rem;
    }
    
    .hide-mobile {
        display: none;
    }
    
    .desktop-actions {
        display: none;
    }
    
    .mobile-actions {
        display: block;
    }
    
    .modal-header {
        padding: 1.2rem;
    }
    
    .modal-header h3 {
        font-size: 1.2rem;
    }
    
    .editor-toolbar {
        padding: 0.8rem;
    }
    
    .toolbar-group {
        width: 100%;
        justify-content: center;
    }
    
    .editor-status {
        width: 100%;
        text-align: center;
    }
    
    .modal-footer {
        padding: 1.2rem;
        flex-direction: column;
    }
    
    .modal-footer .btn {
        width: 100%;
        margin-bottom: 0.5rem;
    }
    
    /* 调整编辑器最小高度 */
    .editor-container {
        min-height: 300px;
    }
    
    #editor {
        min-height: 300px;
    }
}

/* 响应式设计 - 小屏手机 */
@media (max-width: 480px) {
    .breadcrumb {
        font-size: 0.8rem;
    }
    
    .file-list th,
    .file-list td {
        padding: 0.6rem;
        font-size: 0.8rem;
    }
    
    .responsive-modal {
        width: 100%;
        height: 100%;
        max-height: 100vh;
        border-radius: 0;
        margin: 0;
    }
    
    .editor-container {
        min-height: 250px;
    }
    
    #editor {
        min-height: 250px;
    }
    
    .modal-header,
    .modal-footer {
        padding: 1rem;
    }
}

/* 动画效果 */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.file-item {
    animation: fadeIn 0.3s ease;
}

/* 文件类型颜色 */
.text-primary { color: #007bff !important; }
.text-warning { color: #ffc107 !important; }
.text-info { color: #17a2b8 !important; }
.text-success { color: #28a745 !important; }
.text-danger { color: #dc3545 !important; }

/* 操作按钮悬停效果 */
.action-btn:hover {
    opacity: 0.9;
    transform: translateY(-1px);
}

/* 确保编辑器在模态框中正确显示 */
.monaco-editor {
    border-radius: 0 0 8px 8px;
}

/* 滚动条样式 */
.table-responsive::-webkit-scrollbar {
    height: 8px;
}

.table-responsive::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-responsive::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.table-responsive::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 确保移动端友好的触摸目标 */
@media (max-width: 768px) {
    .breadcrumb-item,
    .btn,
    .action-btn,
    .form-select {
        min-height: 44px; /* 最小触摸目标尺寸 */
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .file-list tr {
        min-height: 60px; /* 确保行高足够用于触摸 */
    }
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
    .file-browser,
    .file-list table,
    .modal-content,
    .responsive-modal {
        background: #2d3748;
        color: #e2e8f0;
    }
    
    .file-list th {
        background: #4a5568;
        color: #e2e8f0;
    }
    
    .breadcrumb {
        background: #4a5568;
        border-color: #718096;
    }
    
    .editor-toolbar,
    .modal-footer {
        background: #4a5568;
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs/loader.js"></script>
<script>
// 配置Monaco Editor
require.config({ 
    paths: { 
        'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs' 
    } 
});

// 预加载Monaco Editor
let monacoEditorReady = false;

require(['vs/editor/editor.main'], function() {
    window.monacoLoaded = true;
    monacoEditorReady = true;
    console.log('Monaco Editor loaded successfully');
    
    // 如果页面加载时已经有要打开的文件，立即打开编辑器
    if (window.pendingFileOpen) {
        openFile(window.pendingFileOpen.path, window.pendingFileOpen.content, window.pendingFileOpen.mimeType);
        window.pendingFileOpen = null;
    }
});

// 添加错误处理
window.addEventListener('error', function(e) {
    if (e.message.includes('monaco')) {
        console.error('Monaco Editor loading error:', e);
        // 可以在这里提供备选方案或显示错误信息
    }
});
</script>

<script>
// 全局变量
let currentPath = "{{ current_path }}";
let editor = null;
let currentFile = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadFileList(currentPath);
    initializeBreadcrumb();
    setupResponsiveLayout();
    
    // 添加全局点击事件关闭模态框
    document.addEventListener('click', function(event) {
        const modal = document.getElementById('actionModal');
        if (event.target === modal) {
            closeActionModal();
        }
    });
    
    // 添加ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeActionModal();
        }
    });
});

// 设置响应式布局
function setupResponsiveLayout() {
    const isMobile = window.innerWidth <= 768;
    if (isMobile) {
        document.body.classList.add('mobile-view');
    }
}

// 加载文件列表
async function loadFileList(path) {
    const fileListBody = document.getElementById('fileListBody');
    fileListBody.innerHTML = '<tr><td colspan="5" class="loading">加载中...</td></tr>';
    
    try {
        const response = await fetch('/list_files?path=' + encodeURIComponent(path));
        const data = await response.json();
        
        if (data.success) {
            renderFileList(data.files);
        } else {
            fileListBody.innerHTML = '<tr><td colspan="5" class="error">加载失败: ' + data.error + '</td></tr>';
        }
    } catch (error) {
        fileListBody.innerHTML = '<tr><td colspan="5" class="error">请求失败: ' + error + '</td></tr>';
    }
}

// 渲染文件列表
function renderFileList(files) {
    const fileListBody = document.getElementById('fileListBody');
    let html = '';
    
    if (files.length === 0) {
        html = '<tr><td colspan="5" class="empty">空文件夹</td></tr>';
        fileListBody.innerHTML = html;
        return;
    }
    
    // 先显示文件夹
    files.filter(file => file.is_dir).forEach(file => {
        html += createFileRow(file);
    });
    
    // 再显示文件
    files.filter(file => !file.is_dir).forEach(file => {
        html += createFileRow(file);
    });
    
    fileListBody.innerHTML = html;
    
    // 添加移动端触摸事件
    addMobileTouchEvents();
}

function createFileRow(file) {
    const icon = file.is_dir ? 'fas fa-folder text-warning' : getFileIcon(file.name);
    const type = file.is_dir ? '文件夹' : getFileType(file.name);
    const size = file.is_dir ? '-' : formatFileSize(file.size);
    
    return `
        <tr class="file-item" data-path="${file.path}" data-type="${file.is_dir ? 'folder' : 'file'}">
            <td onclick="${file.is_dir ? `navigateTo('${file.path}')` : `openFile('${file.path}')`}" 
                style="cursor: pointer;" class="file-info-cell">
                <div class="file-info-content">
                    <i class="${icon} file-icon"></i>
                    <div class="file-details">
                        <div class="file-name">${file.name}</div>
                        <div class="file-meta mobile-only">
                            <span class="file-type">${type}</span>
                            <span class="file-size">${size}</span>
                            <span class="file-date">${file.modified}</span>
                        </div>
                    </div>
                </div>
            </td>
            <td class="hide-mobile">${type}</td>
            <td class="hide-mobile">${size}</td>
            <td class="hide-tablet">${file.modified}</td>
            <td class="file-actions-cell">
                <!-- 桌面端操作按钮 - 修改为文字按钮 -->
                <div class="desktop-actions">
                    ${!file.is_dir ? `
                        <button onclick="openFile('${file.path}')" class="action-btn btn-edit" title="编辑">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button onclick="downloadFile('${file.path}')" class="action-btn btn-download" title="下载">
                            <i class="fas fa-download"></i> 下载
                        </button>
                    ` : ''}
                    <button onclick="renameItem('${file.path}', '${file.is_dir ? 'folder' : 'file'}')" 
                            class="action-btn btn-rename" title="重命名">
                        <i class="fas fa-i-cursor"></i> 重命名
                    </button>
                    <button onclick="deleteItem('${file.path}', '${file.is_dir ? 'folder' : 'file'}')" 
                            class="action-btn btn-delete" title="删除">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
                
                <!-- 移动端操作按钮组 - 修改为文字按钮 -->
                <div class="mobile-actions">
                    <div class="mobile-action-buttons">
                        ${!file.is_dir ? `
                            <button onclick="openFile('${file.path}')" class="mobile-action-btn btn-edit" title="编辑">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button onclick="downloadFile('${file.path}')" class="mobile-action-btn btn-download" title="下载">
                                <i class="fas fa-download"></i> 下载
                            </button>
                        ` : ''}
                        <button onclick="renameItem('${file.path}', '${file.is_dir ? 'folder' : 'file'}')" 
                                class="mobile-action-btn btn-rename" title="重命名">
                            <i class="fas fa-i-cursor"></i> 重命名
                        </button>
                        <button onclick="deleteItem('${file.path}', '${file.is_dir ? 'folder' : 'file'}')" 
                                class="mobile-action-btn btn-delete" title="删除">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            </td>
        </tr>
    `;
}

// 处理移动端操作
function handleMobileAction(select, path, isDir) {
    const action = select.value;
    select.value = '';
    
    switch(action) {
        case 'edit':
            openFile(path);
            break;
        case 'download':
            downloadFile(path);
            break;
        case 'rename':
            renameItem(path, isDir ? 'folder' : 'file');
            break;
        case 'delete':
            deleteItem(path, isDir ? 'folder' : 'file');
            break;
    }
}

// 打开文件
async function openFile(filePath) {
    try {
        const response = await fetch('/read_file?path=' + encodeURIComponent(filePath));
        const data = await response.json();
        
        if (data.success) {
            currentFile = filePath;
            
            // 检查Monaco Editor是否已加载完成
            if (monacoEditorReady) {
                openEditor(filePath, data.content, data.mime_type);
            } else {
                // 如果Monaco Editor还没加载完成，先保存文件信息，等加载完成后再打开
                window.pendingFileOpen = {
                    path: filePath,
                    content: data.content,
                    mimeType: data.mime_type
                };
                
                // 显示加载提示
                showAlert('编辑器正在加载中，请稍候...', 'info');
                
                // 设置超时检查
                const checkInterval = setInterval(() => {
                    if (monacoEditorReady && window.pendingFileOpen) {
                        clearInterval(checkInterval);
                        openEditor(window.pendingFileOpen.path, window.pendingFileOpen.content, window.pendingFileOpen.mimeType);
                        window.pendingFileOpen = null;
                    }
                }, 500);
            }
        } else {
            showAlert('打开文件失败: ' + data.error, 'error');
        }
    } catch (error) {
        showAlert('请求失败: ' + error, 'error');
    }
}

// 打开编辑器
function openEditor(filePath, content, mimeType) {
    try {
        document.getElementById('editorTitle').textContent = '编辑: ' + filePath;
        document.getElementById('editorModal').style.display = 'flex';
        
        // 确保Monaco Editor已加载
        if (typeof monaco === 'undefined') {
            showAlert('编辑器加载中，请稍候...', 'info');
            return;
        }
        
        // 销毁现有的编辑器实例（如果存在）
        if (editor) {
            editor.dispose();
            editor = null;
        }
        
        // 创建新的编辑器实例
        editor = monaco.editor.create(document.getElementById('editor'), {
            value: content,
            language: getLanguageFromExt(filePath),
            theme: 'vs-dark',
            automaticLayout: true,
            minimap: { enabled: true },
            scrollBeyondLastLine: false,
            fontSize: 14,
            lineNumbers: 'on',
            folding: true,
            wordWrap: 'on'
        });
        
        // 添加编辑器调整大小监听
        window.addEventListener('resize', function() {
            if (editor) {
                editor.layout();
            }
        });
        
    } catch (error) {
        console.error('编辑器初始化错误:', error);
        showAlert('编辑器初始化失败: ' + error.message, 'error');
        
        // 提供备选方案：使用textarea
        provideFallbackEditor(filePath, content);
    }
}

// 保存文件
async function saveFile() {
    if (!editor || !currentFile) return;
    
    const content = editor.getValue();
    
    try {
        const response = await fetch('/write_file', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                path: currentFile,
                content: content
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('文件保存成功', 'success');
            closeEditor();
        } else {
            showAlert('保存失败: ' + data.error, 'error');
        }
    } catch (error) {
        showAlert('请求失败: ' + error, 'error');
    }
}

// 下载文件
function downloadFile(filePath) {
    window.open('/download_file?path=' + encodeURIComponent(filePath), '_blank');
}

// 重命名 - 修改为默认输入文件原名
async function renameItem(oldPath, type) {
    const fileName = oldPath.split('/').pop(); // 获取文件名
    const newName = prompt('请输入新的名称:', fileName); // 默认显示原文件名
    
    if (!newName || newName === fileName) return; // 如果没有输入或名称相同，不执行操作
    
    const newPath = oldPath.split('/').slice(0, -1).join('/') + '/' + newName;
    
    try {
        const response = await fetch('/rename_item', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                old_path: oldPath,
                new_path: newPath,
                type: type
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('重命名成功', 'success');
            loadFileList(currentPath);
        } else {
            showAlert('重命名失败: ' + data.error, 'error');
        }
    } catch (error) {
        showAlert('请求失败: ' + error, 'error');
    }
}

// 删除确认函数
async function deleteItem(path, type) {
    showActionModal(
        '确认删除',
        `确定要删除${type === 'folder' ? '文件夹' : '文件'} "${path.split('/').pop()}" 吗？<br><small style="color: #666;">此操作不可撤销！</small>`,
        () => performDelete(path, type)
    );
}

async function performDelete(path, type) {
    try {
        const response = await fetch('/delete_item', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                path: path,
                type: type
            })
        });
        
        const data = await response.json();
        
        // 关闭模态框
        closeActionModal();
        
        if (data.success) {
            showAlert('删除成功', 'success');
            // 刷新文件列表
            loadFileList(currentPath);
        } else {
            showAlert('删除失败: ' + data.error, 'error');
        }
    } catch (error) {
        // 关闭模态框
        closeActionModal();
        showAlert('请求失败: ' + error, 'error');
    }
}

// 确保模态框关闭函数正确工作
function closeActionModal() {
    const modal = document.getElementById('actionModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 添加移动端触摸事件支持
function addMobileTouchEvents() {
    if (window.innerWidth <= 768) {
        document.querySelectorAll('.file-item').forEach(item => {
            item.addEventListener('touchstart', function(e) {
                this.style.backgroundColor = '#f0f6ff';
            });
            
            item.addEventListener('touchend', function(e) {
                this.style.backgroundColor = '';
            });
        });
    }
}

// 显示操作确认模态框
function showActionModal(title, message, confirmCallback) {
    const modal = document.getElementById('actionModal');
    if (!modal) return;
    
    document.getElementById('actionModalTitle').textContent = title;
    document.getElementById('actionModalMessage').innerHTML = message;
    
    const confirmBtn = document.getElementById('actionConfirmBtn');
    if (confirmBtn) {
        // 移除旧的事件监听器
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        
        // 添加新的事件监听器
        newConfirmBtn.onclick = function() {
            if (typeof confirmCallback === 'function') {
                confirmCallback();
            }
        };
    }
    
    modal.style.display = 'flex';
    
    // 添加模态框关闭事件
    const closeBtn = modal.querySelector('.close');
    if (closeBtn) {
        closeBtn.onclick = closeActionModal;
    }
}

// 关闭操作确认模态框
function closeActionModal() {
    document.getElementById('actionModal').style.display = 'none';
}

// 显示提示信息
function showAlert(message, type) {
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.textContent = message;
    alert.style.position = 'fixed';
    alert.style.top = '20px';
    alert.style.right = '20px';
    alert.style.zIndex = '1000';
    alert.style.padding = '10px 20px';
    alert.style.borderRadius = '4px';
    alert.style.color = 'white';
    alert.style.backgroundColor = type === 'success' ? '#28a745' : '#dc3545';
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        alert.remove();
    }, 3000);
}

// 辅助函数：获取文件图标
function getFileIcon(filename) {
    const ext = filename.split('.').pop().toLowerCase();
    const iconMap = {
        'py': 'fas fa-file-code text-primary',
        'js': 'fas fa-file-code text-warning',
        'html': 'fas fa-file-code text-info',
        'css': 'fas fa-file-code text-primary',
        'json': 'fas fa-file-code text-warning',
        'xml': 'fas fa-file-code text-info',
        'md': 'fas fa-file-alt',
        'txt': 'fas fa-file-alt',
        'jpg': 'fas fa-file-image text-success',
        'jpeg': 'fas fa-file-image text-success',
        'png': 'fas fa-file-image text-success',
        'gif': 'fas fa-file-image text-success',
        'mp4': 'fas fa-file-video text-danger',
        'avi': 'fas fa-file-video text-danger',
        'mov': 'fas fa-file-video text-danger'
    };
    return iconMap[ext] || 'fas fa-file';
}

// 辅助函数：获取文件类型
function getFileType(filename) {
    const ext = filename.split('.').pop().toLowerCase();
    const typeMap = {
        'py': 'Python文件',
        'js': 'JavaScript文件',
        'html': 'HTML文件',
        'css': 'CSS文件',
        'json': 'JSON文件',
        'xml': 'XML文件',
        'md': 'Markdown文件',
        'txt': '文本文件',
        'jpg': '图片文件',
        'jpeg': '图片文件',
        'png': '图片文件',
        'gif': '图片文件',
        'mp4': '视频文件',
        'avi': '视频文件',
        'mov': '视频文件'
    };
    return typeMap[ext] || '文件';
}

// 辅助函数：格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 辅助函数：导航到路径
function navigateTo(path) {
    currentPath = path;
    loadFileList(path);
    updateBreadcrumb(path);
}

// 辅助函数：更新面包屑导航
function updateBreadcrumb(path) {
    const breadcrumb = document.querySelector('.breadcrumb');
    let html = '<span class="breadcrumb-item" data-path="">根目录</span>';
    
    if (path) {
        const parts = path.split('/').filter(part => part);
        let currentPath = '';
        
        parts.forEach((part, index) => {
            currentPath += (currentPath ? '/' : '') + part;
            html += `
                <span class="breadcrumb-separator">/</span>
                <span class="breadcrumb-item" data-path="${currentPath}">${part}</span>
            `;
        });
    }
    
    breadcrumb.innerHTML = html;
    initializeBreadcrumb();
}

// 辅助函数：初始化面包屑导航
function initializeBreadcrumb() {
    const breadcrumbItems = document.querySelectorAll('.breadcrumb-item');
    breadcrumbItems.forEach(item => {
        const path = item.dataset.path;
        item.addEventListener('click', () => {
            if (path !== undefined) {
                navigateTo(path);
            }
        });
    });
}

// 辅助函数：获取文件扩展名对应的语言
function getLanguageFromExt(filePath) {
    const ext = filePath.split('.').pop().toLowerCase();
    const languageMap = {
        'py': 'python',
        'js': 'javascript',
        'html': 'html',
        'css': 'css',
        'json': 'json',
        'xml': 'xml',
        'md': 'markdown'
    };
    return languageMap[ext] || 'plaintext';
}

// 辅助函数：关闭编辑器
function closeEditor() {
    document.getElementById('editorModal').style.display = 'none';
    if (editor) {
        editor.dispose();
        editor = null;
    }
    currentFile = null;
}

// 辅助函数：刷新文件列表
function refreshFileList() {
    loadFileList(currentPath);
}

// 辅助函数：创建新文件
function createNewFile() {
    const fileName = prompt('请输入新文件名:');
    if (!fileName) return;
    
    const filePath = currentPath ? currentPath + '/' + fileName : fileName;
    
    fetch('/create_file', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            path: filePath,
            content: ''
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('文件创建成功', 'success');
            refreshFileList();
        } else {
            showAlert('创建失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        showAlert('请求失败: ' + error, 'error');
    });
}

// 辅助函数：创建新文件夹
function createNewFolder() {
    const folderName = prompt('请输入新文件夹名:');
    if (!folderName) return;
    
    const folderPath = currentPath ? currentPath + '/' + folderName : folderName;
    
    fetch('/create_folder', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            path: folderPath
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('文件夹创建成功', 'success');
            refreshFileList();
        } else {
            showAlert('创建失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        showAlert('请求失败: ' + error, 'error');
    });
}

// 辅助函数：上传文件
function uploadFile() {
    const input = document.createElement('input');
    input.type = 'file';
    input.multiple = true;
    
    input.onchange = function(e) {
        const files = e.target.files;
        if (files.length === 0) return;
        
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append('files', files[i]);
        }
        formData.append('path', currentPath);
        
        fetch('/upload_files', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
            showAlert('文件上传成功', 'success');
            refreshFileList();
        } else {
            showAlert('上传失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        showAlert('请求失败: ' + error, 'error');
    });
    };
    
    input.click();
}

// 编辑器功能函数
function editorUndo() {
    if (editor) {
        editor.trigger('keyboard', 'undo');
    }
}

function editorRedo() {
    if (editor) {
        editor.trigger('keyboard', 'redo');
    }
}

function editorFind() {
    if (editor) {
        editor.trigger('editor', 'actions.find');
    }
}

function editorReplace() {
    if (editor) {
        editor.trigger('editor', 'editor.action.startFindReplaceAction');
    }
}

function reloadFile() {
    if (currentFile) {
        openFile(currentFile);
    }
}

// 提供备选编辑器方案
function provideFallbackEditor(filePath, content) {
    document.getElementById('editorTitle').textContent = '编辑: ' + filePath;
    document.getElementById('editorModal').style.display = 'flex';
    
    const editorContainer = document.getElementById('editorContainer');
    editorContainer.innerHTML = `
        <textarea id="fallbackEditor" style="width: 100%; height: 400px; font-family: monospace; padding: 10px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;">${content}</textarea>
    `;
    
    // 保存文件时使用备选方案
    window.fallbackSaveFile = function() {
        const content = document.getElementById('fallbackEditor').value;
        
        fetch('/write_file', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                path: currentFile,
                content: content
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('文件保存成功', 'success');
                closeEditor();
            } else {
                showAlert('保存失败: ' + data.error, 'error');
            }
        })
        .catch(error => {
            showAlert('请求失败: ' + error, 'error');
        });
    };
}
</script>
{% endblock %}
